package ar.com.ford.it.fullEconomics.logic;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.CurrencyDao;
import ar.com.ford.it.fullEconomics.persistence.dao.EconomicValueDao;
import ar.com.ford.it.fullEconomics.persistence.dao.LogDao;
import ar.com.ford.it.fullEconomics.persistence.dao.PartDao;
import ar.com.ford.it.fullEconomics.persistence.dao.PricingDao;
import ar.com.ford.it.fullEconomics.persistence.dao.SupplyDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesm01Currency;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp04Supply;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp05Pricing;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx03Intflog;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx04Intflevent;
import ar.com.ford.it.fullEconomics.struct.CounterStruct;
import ar.com.ford.it.fullEconomics.struct.PricingStruct;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class PricingLogic {
    private static final String CLASS_NAME = PricingLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * Se busca el pricing segun los filtros , proveedor, parte y fecha
     * efectivas
     * 
     * @param pricing
     * @param fechaInStart
     * @param fechaInEnd
     * @param fechaOutStart
     * @param fechaOutEnd
     * @return
     * @throws FullEconomicsException
     */
    public Collection<PricingStruct> findPricing(Teesp05Pricing pricing,
                                                 Timestamp fechaInStart,
                                                 Timestamp fechaInEnd,
                                                 Timestamp fechaOutStart,
                                                 Timestamp fechaOutEnd)
            throws FullEconomicsException {

        String METHOD_NAME = "findPricing";
        log.entering(CLASS_NAME, METHOD_NAME);
        PricingDao dao = new PricingDao();
        Collection<Teesp05Pricing> ret = null;
        Collection<PricingStruct> result = new ArrayList<PricingStruct>();

        try {
            ret = dao.findPricing(pricing, fechaInStart, fechaInEnd,
                    fechaOutStart, fechaOutEnd);
            if (!ret.isEmpty()) {
                for (Teesp05Pricing pric : ret) {
                    PricingStruct newPricing = new PricingStruct();
                    newPricing.setPricing(pric);
                    newPricing.setSherePorc(pric.getTeesp04Supply()
                            .getEesp04SupplySharePercentP());
                    result.add(newPricing);
                }
            }

        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Pricing Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.FINDALL);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;

    }

    /**
     * Crea un pricing si cumple las condiciones de que el supply exista
     * 
     * @param pricing
     * @param user
     * @throws FullEconomicsException
     */
    public void createPricing(Teesp05Pricing pricing, FullEconomicsWslxUser user)
            throws FullEconomicsException {
        String METHOD_NAME = "createPricing";
        log.entering(CLASS_NAME, METHOD_NAME);

        PricingDao dao = new PricingDao();
        SupplyDao supplyDao = new SupplyDao();
        Teesp05Pricing newPricing = new Teesp05Pricing();
        Teesp05Pricing workingCopy = null;

        try {
            PersistenceUtil.newTransaction();
            // busco si existen pricings con fecha de cierre dentro del rango
            // ingresado por el usuario. Debe haber como mucho uno solo
            Collection<Teesp05Pricing> existingPrincing = dao
                    .findPricingExisting(pricing, pricing
                            .getEesp05PriceEffectiveDateY(), pricing
                            .getEesp05PriceEndDateY(), new Integer(1));
            if (!existingPrincing.isEmpty()) {
                workingCopy = dao.getUpdatePricing(existingPrincing.iterator()
                        .next());
                workingCopy.setEesp05PriceEndDateY(FullEconomicsDateUtil
                        .fechaMas(pricing.getEesp05PriceEffectiveDateY(), -1));
            }
            newPricing.setEesp05PlantCodeC(user.getTeesg01Plant());
            Teesp04Supply supply = supplyDao.getUpdateSupply(pricing
                    .getTeesp04Supply());
            newPricing.setTeesp04Supply(supply);

            newPricing.setEesp05CreateUserC(user.getId());
            newPricing.setEesp05CreateS(new Timestamp(System
                    .currentTimeMillis()));
            newPricing.setEesp05LastUpdtUserC(user.getId());
            newPricing.setEesp05LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            newPricing.setEesp05CurrencyCodeC((new CurrencyDao())
                    .getCurrencyForUpdate(pricing.getEesp05CurrencyCodeC()
                            .getEesm01CurrencyCodeC()));
            newPricing.setEesp05PriceAmountA(pricing.getEesp05PriceAmountA());
            newPricing.setEesp05PriceEffectiveDateY(pricing
                    .getEesp05PriceEffectiveDateY());
            newPricing.setEesp05PriceEndDateY(pricing.getEesp05PriceEndDateY());
            newPricing.setTeesx03Intflog(pricing.getTeesx03Intflog());
            dao.createPricing(newPricing);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Pricing Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Pricing.CREATE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Actualizacion de Pricing
     * 
     * @param pricing
     * @throws FullEconomicsException
     */
    public void updatePricing(Teesp05Pricing pricing, FullEconomicsWslxUser user)
            throws FullEconomicsException {
        String METHOD_NAME = "updatePricing";
        log.entering(CLASS_NAME, METHOD_NAME);
        Teesp05Pricing workingCopy = new Teesp05Pricing();
        workingCopy.setEesp05CurrencyCodeC(new Teesm01Currency());
        try {

            PersistenceUtil.newTransaction();
            PersistenceUtil.getPersistenceManager().clearCache();
            workingCopy = (new PricingDao()).getUpdatePricing(pricing);
            workingCopy.setEesp05CurrencyCodeC((new CurrencyDao())
                    .getCurrencyForUpdate(pricing.getEesp05CurrencyCodeC()
                            .getEesm01CurrencyCodeC()));
            workingCopy.setEesp05PriceAmountA(pricing.getEesp05PriceAmountA());
            workingCopy
                    .setEesp05PriceEndDateY(pricing.getEesp05PriceEndDateY());
            workingCopy.setTeesx03Intflog(null);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {

            pe.printStackTrace();
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Pricing Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Pricing.UPDATE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Elimina el pricing
     * 
     * @param pricing
     * @return
     * @throws FullEconomicsException
     */
    public boolean deletedPricing(Teesp05Pricing pricing)
            throws FullEconomicsException {
        String METHOD_NAME = "deleteEconomicValue";
        log.entering(CLASS_NAME, METHOD_NAME);
        boolean res = true;
        try {
            PersistenceUtil.newTransaction();
            PricingDao dao = new PricingDao();
            dao.deletePricing(pricing);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            res = false;
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Deleted Pricing Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.DELETE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Busca todos los prcing segun la pk
     * 
     * @param pricing
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesp05Pricing> findAllPricing(Teesp05Pricing pricing)
            throws FullEconomicsException {

        String METHOD_NAME = "findAllPricing";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesp05Pricing> res = null;
        EconomicValueDao dao = new EconomicValueDao();
        String[] fields = { "eesp05PlantCodeC", "teesp04Supply" };
        Object[] values = { pricing.getEesp05PlantCodeC(),
                pricing.getTeesp04Supply() };

        try {
            res = dao.findAll(new Teesp05Pricing(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find all Pricing Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.FINDALL);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Elimina el pricing
     * 
     * @param pricing
     * @return
     * @throws FullEconomicsException
     */
    public boolean overloadDateEffective(Timestamp fechaInStart,
                                         Timestamp fechaInEnd,
                                         Timestamp fechaOutStart,
                                         Timestamp fechaOutEnd)
            throws FullEconomicsException {
        String METHOD_NAME = "overloadDateEffective";
        log.entering(CLASS_NAME, METHOD_NAME);
        PricingDao dao = new PricingDao();
        boolean res = true;
        try {
            if (dao.overloadDateEffective(fechaInStart, fechaInEnd,
                    fechaOutStart, fechaOutEnd) == null) {
                res = false;
            }
        } catch (PersistenceException e) {
            res = false;
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Overload Date Pricing Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.OVERLOADDATE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Verifica la existencia del supply el cual se utilizara para la creacion
     * de pricing
     * 
     * @param pricing
     * @return
     * @throws FullEconomicsException
     */
    public boolean verificSupply(Teesp05Pricing pricing)
            throws FullEconomicsException {
        String METHOD_NAME = "verificSupply";
        log.entering(CLASS_NAME, METHOD_NAME);
        boolean res = false;
        SupplyLogic supplyLogic = new SupplyLogic();
        if (supplyLogic.getSupplyByPk(pricing.getTeesp04Supply()) != null) {
            res = true;
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Verifica que la parte exista
     * 
     * @param part
     * @return
     * @throws FullEconomicsException
     */
    public Teesp01Part findPart(Teesg01Plant plant, String classCode,
                                String prefijo, String base, String sufijo)
            throws FullEconomicsException {
        String METHOD_NAME = "overloadDateEffective";
        log.entering(CLASS_NAME, METHOD_NAME);
        PartDao dao = new PartDao();
        Teesp01Part res = new Teesp01Part();
        try {

            res.setEesp01PartClassCodeC(classCode);
            res.setEesp01PlantCodeC(plant);
            res.setEesp01PartPrefixCodeC(prefijo);
            res.setEesp01PartBaseCodeC(base);
            res.setEesp01PartSuffixCodeC(sufijo);
            res = dao.findPartByPk(res);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Ceked Part Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.NOEXISTEPARTE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Verifica si existe el pricing
     * 
     * @param pricing
     * @param fechaInS
     * @param fechaInE
     * @return
     * @throws FullEconomicsException
     */
    public Boolean findPricingExisting(Teesp05Pricing pricing,
                                       Timestamp fechaInS, Timestamp fechaInE)
            throws FullEconomicsException {
        String METHOD_NAME = "findPricingExisting";
        log.entering(CLASS_NAME, METHOD_NAME);
        PricingDao dao = new PricingDao();
        boolean result = true;
        Collection<Teesp05Pricing> ret = null;

        try {
            ret = dao.findPricingExisting(pricing, fechaInS, fechaInE,
                    new Integer(0));
            if (!ret.isEmpty()) {
                return false;
            }
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "fechaInE Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.FINDALL);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;

    }

    /**
     * Busca el Price de un Supply en una determinada fecha
     * 
     * @param supply
     * @param date
     * @return
     * @throws FullEconomicsException
     */
    public Teesp05Pricing findPricingByDate(Teesp04Supply supply, Timestamp date)
            throws FullEconomicsException {
        String METHOD_NAME = "findPricingByDate";
        PricingDao pricingDao = new PricingDao();
        Teesp05Pricing pricing = null;

        try {
            pricing = pricingDao.findPricingByDate(supply, date);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Pricing by Date Exception", e);

            // FIXME Cambiar mensaje de error
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.FINDALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return pricing;
    }

    /**
     * Crea los precios leidos del archivo de ceps
     * 
     * @param prices
     * @param userId
     * @param logNumber
     * @throws FullEconomicsException
     */
    public CounterStruct insertCepsPrices(Collection<Teesp05Pricing> prices,
                                 String userId, Teesx03Intflog logNumber)
            throws FullEconomicsException {
        String METHOD_NAME = "insertCepsPrices";
        log.entering(CLASS_NAME, METHOD_NAME);
        Teesp05Pricing workingCopy = null;
        PricingDao dao = new PricingDao();
        CurrencyDao currDao = new CurrencyDao();
        LogDao logDao = new LogDao();
        CurrencyLogic currLogic = new CurrencyLogic();
        SupplyLogic supplyLogic = new SupplyLogic();
        PartLogic partLogic = new PartLogic();
        SupplierLogic supplierLogic = new SupplierLogic();
        LogProcessLogic logLogic = new LogProcessLogic();
        Collection<Teesg01Plant> plantasObj;
        boolean findPlant = false;
        int countLine = 0;
        CounterStruct counter = new CounterStruct();
        try {
            plantasObj = dao.findAll(new Teesg01Plant(), null, null);
            for (Teesp05Pricing aPrice : prices) {
                for (Teesg01Plant plant : plantasObj) {
                    if (plant.getEesg01PlantAlternateCodeC().equalsIgnoreCase(
                            aPrice.getEesp05PlantCodeC()
                                    .getEesg01PlantAlternateCodeC())) {

                        FullEconomicsWslxUser user = new FullEconomicsWslxUser(
                                userId);
                        user.setTeesg01Plant(plant);
                        countLine++;
                        aPrice.setEesp05PlantCodeC(plant);
                        aPrice.getTeesp04Supply().setEesp04PlantCodeC(plant);
                        aPrice.getTeesp04Supply().getTeesp01Part()
                                .setEesp01PlantCodeC(plant);
                        aPrice.getTeesp04Supply().getTeess01Supplier()
                                .setEess01PlantCodeC(plant);
                        
                        // busco el currency, si no lo encuentra, lo crea
                        Teesm01Currency currency = currLogic
                                .findCurrencyByCode(aPrice
                                        .getEesp05CurrencyCodeC()
                                        .getEesm01CurrencyCodeC());
                        if (currency == null) {
                            currency = aPrice.getEesp05CurrencyCodeC();
                            Calendar dateIn = Calendar.getInstance();
                            Calendar dateOut = Calendar.getInstance();
                            dateIn.setTimeInMillis(aPrice
                                    .getEesp05PriceEffectiveDateY().getTime());
                            currency.setEesm01CurrencyInDateY(dateIn);
                            dateOut.setTimeInMillis(aPrice
                                    .getEesp05PriceEndDateY().getTime());
                            currency.setEesm01CurrencyOutDateY(dateOut);
                            currency.setTeesx03Intflog(logNumber);
                            currLogic.createCurrency(aPrice
                                    .getEesp05CurrencyCodeC(), user);
                        }
                        aPrice.setEesp05CurrencyCodeC(currency);
                        
                        // busco la pieza, si no la encuentra la creo
                        Teesp01Part part = partLogic.findPartByPk(aPrice
                                .getTeesp04Supply().getTeesp01Part());
                        if (part == null) {
                            part = aPrice.getTeesp04Supply().getTeesp01Part();
                            part.setTeesx03Intflog(logNumber);
                            part.setEesp01PartInDateY(aPrice
                                    .getEesp05PriceEffectiveDateY());
                            part.setEesp01PartOutDateY(aPrice
                                    .getEesp05PriceEndDateY());
                            part
                                    .setEesp01PartDescriptionX("FullEE Interface generated part");
                            partLogic.createPart(part, user);
                        }
                        
                        // buco el proveedor, si no lo encuentra, lo crea
                        Teess01Supplier supplier = supplierLogic
                                .getSupplierByPk(aPrice.getTeesp04Supply()
                                        .getTeess01Supplier());
                        if (supplier == null) {
                            supplier = aPrice.getTeesp04Supply()
                                    .getTeess01Supplier();
                            supplier.setTeesx03Intflog(logNumber);
                            supplierLogic.createSupplier(supplier, user);
                        }
                        
                        // busco el supply, si no lo encuentra lo creo
                        Teesp04Supply supply = supplyLogic.getSupplyByPk(aPrice
                                .getTeesp04Supply());
                        if (supply == null) {
                            supply = aPrice.getTeesp04Supply();
                            supply.setTeesx03Intflog(logNumber);
                            supplyLogic.createSupply(aPrice.getTeesp04Supply(),
                                    user);
                        }

                        PersistenceUtil.newTransaction();
                        logNumber = logDao.getIntflogyUpdate(logNumber);
                        workingCopy = dao.getUpdatePricing(aPrice);
                        String modif = null;
                        if (workingCopy != null ) {
                            // Actualizo el pricing 
                        	
                        	// ??? workingCopy.getEesp05PriceEndDateY().after(aPrice.getEesp05PriceEndDateY())????
                        	// (workingCopy.getEesp05PriceAmountA().compareTo(aPrice.getEesp05PriceAmountA())!=0)

                            modif = this.modificationDescription(workingCopy,aPrice);
                            workingCopy.setEesp05PriceAmountA(aPrice.getEesp05PriceAmountA());
                            
                            
                            workingCopy.setEesp05PriceEndDateY(aPrice.getEesp05PriceEndDateY()); // (FechaIN - 1) ?
                            
                            workingCopy.setEesp05CurrencyCodeC(currDao
                                    .getCurrencyForUpdate(aPrice
                                            .getEesp05CurrencyCodeC()
                                            .getEesm01CurrencyCodeC()));
                            workingCopy.setTeesx03Intflog(logNumber);
                            logLogic.insertLogIntfLevent(userId, logNumber,
                                    "U", modif, countLine);
                            counter.addCount();
                        } else {
                        	// Si no lo encuentra lo crea
                            // pero antes busco si existe un precio con fecha de cierre dentro del rango
                             Collection<Teesp05Pricing> existingPrincing = dao
                                     .findPricingExisting(aPrice, aPrice
                                             .getEesp05PriceEffectiveDateY(), aPrice
                                             .getEesp05PriceEndDateY(), new Integer(1));
                             if (!existingPrincing.isEmpty()) {
                                 workingCopy = dao.getUpdatePricing(existingPrincing.iterator()
                                         .next());
                                 workingCopy.setEesp05PriceEndDateY(FullEconomicsDateUtil
                                         .fechaMas(aPrice.getEesp05PriceEffectiveDateY(), -1));
                             }
                        	
                        	///
                        	
                            aPrice.setTeesx03Intflog(logNumber);
                            aPrice.getEesp05CurrencyCodeC().setTeesx03Intflog(logNumber);
                            aPrice.getTeesp04Supply().setTeesx03Intflog(logNumber);
                            aPrice.getTeesp04Supply().getTeesp01Part()
                                    .setTeesx03Intflog(logNumber);
                            aPrice.getTeesp04Supply().getTeess01Supplier()
                                    .setTeesx03Intflog(logNumber);
                            this.createPricing(aPrice, user);
                            counter.addCount();
                        }
                        PersistenceUtil.commitTransaction();
                    }
                }
                if (findPlant) {
                    logLogic.insertLogIntfLevent(userId, logNumber, "W",
                            "Plant '"
                                    + aPrice.getEesp05PlantCodeC()
                                            .getEesg01PlantAlternateCodeC()
                                    + "' not found", countLine);
                    counter.addWarning();
                }
            }

        } catch (PersistenceException e) {
            try {
                logLogic.insertLogIntfLevent(userId, logNumber, "E",
                        "Internal error. proccess canceled", countLine);
                counter.addError();
                this.cepsRollBack(logNumber, userId);
            } catch (PersistenceException e1) {
                logLogic.insertLogIntfLevent(userId, logNumber, "E",
                        "RollBack error", countLine);
                counter.addError();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "insert ceps prices", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Pricing.CEPSPRICING);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return counter;
    }

    /**
     * rollback manual de lo generado por el metodo createC insertCepsPrices
     * 
     * @param logNumber
     * @param userId
     * @throws FullEconomicsException
     * @throws PersistenceException
     */
    private void cepsRollBack(Teesx03Intflog logNumber, String userId)
            throws FullEconomicsException, PersistenceException {
        PricingDao dao = new PricingDao();
        SupplyLogic supplyLogic = new SupplyLogic();
        SupplierLogic supplierLogic = new SupplierLogic();
        PartLogic partLogic = new PartLogic();
        CurrencyLogic currLogic = new CurrencyLogic();

        String[] fields = { "teesx03Intflog" };
        Object[] values = { logNumber };
        String[] eventFields = { "teesx03Intflog", "eesx04IevntTypeCodeC" };
        Object[] eventValues = { logNumber, "U" };

        // busco las modificaciones
        Collection<Teesx04Intflevent> modifEvents = dao.findAll(
                new Teesx04Intflevent(), eventFields, eventValues);
        for (Teesx04Intflevent event : modifEvents) {
            Teesp05Pricing originalPricing = this.getOriginalPricing(event);
            FullEconomicsWslxUser user = new FullEconomicsWslxUser(userId);
            user.setTeesg01Plant(originalPricing.getEesp05PlantCodeC());
            this.updatePricing(originalPricing, user);
        }

        // borro pricings
        Collection<Teesp05Pricing> pricings = dao.findAll(new Teesp05Pricing(),
                fields, values);
        for (Teesp05Pricing pricing : pricings)
            this.deletedPricing(pricing);

        // borro supplies
        Collection<Teesp04Supply> supplies = dao.findAll(new Teesp04Supply(),
                fields, values);
        for (Teesp04Supply supply : supplies)
            supplyLogic.deletedSupply(supply);

        // borro suppliers
        Collection<Teess01Supplier> suppliers = dao.findAll(
                new Teess01Supplier(), fields, values);
        for (Teess01Supplier supplier : suppliers)
            supplierLogic.deleteSupplier(supplier);

        // borro parts
        Collection<Teesp01Part> parts = dao.findAll(new Teesp01Part(), fields,
                values);
        for (Teesp01Part part : parts)
            partLogic.deletePart(part);

        // borro currencys
        Collection<Teesm01Currency> currencys = dao.findAll(
                new Teesm01Currency(), fields, values);
        for (Teesm01Currency currency : currencys)
            currLogic.deleteCurrency(currency);
    }

    /**
     * genera la descripcion dela modificacion hecha a la pieza
     * 
     * @param originalPricing
     * @param newPricing
     * @return
     */
    private String modificationDescription(Teesp05Pricing originalPricing,
                                           Teesp05Pricing newPricing) {
        return "Pricing modified: Plant="
                + newPricing.getEesp05PlantCodeC().getEesg01PlantCodeC()
                + "; Supplier=F-"
                + newPricing.getTeesp04Supply().getTeess01Supplier()
                        .getEess01SupplierCodeC()
                + "; Part="
                + newPricing.getTeesp04Supply().getTeesp01Part().toString()
                + ". Changed Price="
                + originalPricing.getEesp05PriceAmountA()
                + " to "
                + newPricing.getEesp05PriceAmountA()
                + "; End date="
                + FullEconomicsDateUtil.format(originalPricing
                        .getEesp05PriceEndDateY())
                + " to "
                + FullEconomicsDateUtil.format(newPricing
                        .getEesp05PriceEndDateY())
                + "; Currency="
                + originalPricing.getEesp05CurrencyCodeC()
                        .getEesm01CurrencyCodeC() + " to "
                + newPricing.getEesp05CurrencyCodeC().getEesm01CurrencyCodeC()
                + ".";
    }

    // se tiene que corresponder con el metodo modification description
    private Teesp05Pricing getOriginalPricing(Teesx04Intflevent event) {
        Teesp05Pricing pricing = new Teesp05Pricing();
        Teesp04Supply supply = new Teesp04Supply();
        Teesp01Part part = new Teesp01Part();
        Teess01Supplier supplier = new Teess01Supplier();
        Teesm01Currency currency = new Teesm01Currency();
        Teesg01Plant plant = new Teesg01Plant();
        String modif = event.getEesx04IevntMessageDescripX();
        int plantIndex = modif.indexOf("Plant");
        int supplierIndex = modif.indexOf("Supplier");
        int partIndex = modif.indexOf("Part");
        int changeIndex = modif.indexOf("Changed");
        int priceIndex = modif.indexOf("Price");
        int endPriceIndex = modif.indexOf("to", priceIndex) - 1;
        int endDateIndex = modif.indexOf("End date");
        int endEndDateIndex = modif.indexOf("to", endDateIndex) - 1;
        int currencyIndex = modif.indexOf("Currency");
        int endCurrencyIndex = modif.indexOf("to", currencyIndex) - 1;

        String plantCode = modif.substring(plantIndex + 6, supplierIndex - 2);
        String supplierCode = modif
                .substring(supplierIndex + 11, partIndex - 2);
        String partCodes[] = modif.substring(partIndex + 7, changeIndex - 2)
                .split("-");
        String price = modif.substring(priceIndex + 6, endPriceIndex);
        String endDate = modif.substring(endDateIndex + 9, endEndDateIndex);
        String currencyCode = modif.substring(currencyIndex + 9,
                endCurrencyIndex);

        plant.setEesg01PlantCodeC(plantCode);
        supplier.setEess01SupplierClassCodeC("F");
        supplier.setEess01SupplierCodeC(supplierCode);
        supplier.setEess01PlantCodeC(plant);
        part.setEesp01PartClassCodeC("F");
        part.setEesp01PartPrefixCodeC(partCodes[0]);
        part.setEesp01PartBaseCodeC(partCodes[1]);
        part.setEesp01PartSuffixCodeC(partCodes[2]);
        part.setEesp01PlantCodeC(plant);
        currency.setEesm01CurrencyCodeC(currencyCode);
        supply.setTeesp01Part(part);
        supply.setTeess01Supplier(supplier);
        supply.setEesp04PlantCodeC(plant);
        pricing.setTeesp04Supply(supply);
        pricing.setEesp05CurrencyCodeC(currency);
        pricing.setEesp05PriceAmountA(new BigDecimal(price));
        pricing.setEesp05PriceEndDateY(new Timestamp(FullEconomicsDateUtil
                .format(endDate).getTimeInMillis()));
        pricing.setEesp05PlantCodeC(plant);

        return pricing;
    }
}
